
package com.bxd.baodan.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.activity.FindPasswordActivity;
import com.bxd.baodan.activity.FindPwdActivity;
import com.bxd.baodan.activity.LoginActivity;
import com.bxd.baodan.activity.MainActivity;
import com.bxd.baodan.activity.RegistActivity;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.mvp.base.MvpBaseFragment;
import com.bxd.baodan.mvp.login.LoginContract;
import com.bxd.baodan.mvp.login.LoginPresenter;
import com.bxd.baodan.util.ETUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.StringUtil;
import com.bxd.baodan.util.observer.SmsContent;

@SuppressLint("ValidFragment")
public class LoginFragment extends MvpBaseFragment<LoginContract.View, LoginPresenter> implements OnClickListener, LoginContract.View {

    private View v;

    private EditText etAccount;
    private EditText etPassword;
    private LoginInfo loginInfo;
    private ImageView can_see_pwd;
    private boolean canSeePassword = false;
    private TextView findPassword;
    private RelativeLayout mRlLogin;
    private int isVcode = 0;
    private LinearLayout relative_password, relative_vcode;
    private EditText etVcode;
    private TextView btnGetVcode;
    private Boolean isGetVcode = false;
    private int time = -1;
    private SmsContent smsContent;


    public LoginFragment() {
    }

    public LoginFragment(int isVcode) {
        this.isVcode = isVcode;
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what > 0) {
                btnGetVcode.setText(msg.what + "秒后重新获取");
                btnGetVcode.setEnabled(false);
            } else {
                btnGetVcode.setText("重新获取验证码");
                btnGetVcode.setEnabled(true);
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (v == null) {
            v = inflater
                    .inflate(R.layout.activity_login_main, container, false);
        }
        ViewGroup viewGroup = (ViewGroup) v.getParent();
        if (viewGroup != null) {
            viewGroup.removeAllViewsInLayout();
        }

        initView(v);
        return v;

    }

    private void initView(View view) {
        // TODO Auto-generated method stub
        relative_password = (LinearLayout) view
                .findViewById(R.id.relative_password);
        relative_vcode = (LinearLayout) view
                .findViewById(R.id.relative_vcode);
        findPassword = getTextView(view, R.id.find_password);
        if (isVcode == 1) {
            relative_vcode.setVisibility(View.VISIBLE);
            relative_password.setVisibility(View.GONE);
            findPassword.setVisibility(View.GONE);
        } else {
            relative_vcode.setVisibility(View.GONE);
            relative_password.setVisibility(View.VISIBLE);

            if (LoginActivity.question == null
                    || LoginActivity.question.equals("")) {

                findPassword.setVisibility(View.VISIBLE);
            } else {
                findPassword.setVisibility(View.GONE);
            }
        }
        loginInfo = LoginInfo.getInstance(App.getContext());

        can_see_pwd = getImageView(view, R.id.can_see_pwd);
        etAccount = getEditText(view, R.id.account_text);
        etPassword = getEditText(view, R.id.password_input);
        mRlLogin = (RelativeLayout) view.findViewById(R.id.rl_login);

        etVcode = getEditText(view, R.id.et_vcode);
        btnGetVcode = getTextView(view, R.id.get_vcode_btn);


        view.findViewById(R.id.regist).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openActivity(RegistActivity.class);
            }
        });

        view.findViewById(R.id.find_password).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openActivity(FindPwdActivity.class);
            }
        });


        btnGetVcode.setOnClickListener(this);

        can_see_pwd.setOnClickListener(this);
        findPassword.setOnClickListener(this);
        mRlLogin.setOnClickListener(this);

        if (!StringUtil.isEmpty(loginInfo.getAccount())) {
            etAccount.setText(loginInfo.getAccount());
            etPassword.requestFocus();
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    ETUtil.showSoftKeyboard(App.getContext(),
                            etPassword);
                }
            }, 2 * 200);
        } else {
            etAccount.requestFocus();
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    ETUtil.showSoftKeyboard(App.getContext(),
                            etAccount);
                }
            }, 2 * 200);
        }
    }


    public void attemptLogin() {
        if (!ETUtil.isMobileNO(etAccount)) {
            etAccount.setError("输入的手机号码不合格");
            etAccount.requestFocus();
            return;
        }
        if (ETUtil.isNotNull(etAccount, etPassword)) {
            presenter.startLogin();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.can_see_pwd:
                canSeePassword = !canSeePassword;
                if (canSeePassword) {
                    // 显示密码
                    can_see_pwd.setImageResource(R.drawable.see_pwd);
                    etPassword
                            .setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    // 隐藏密码
                    can_see_pwd.setImageResource(R.drawable.eyeclosed);
                    etPassword.setInputType(InputType.TYPE_CLASS_TEXT
                            | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                break;
            case R.id.find_password:
                openActivity(FindPasswordActivity.class);
                break;
            case R.id.rl_login:
                // 登录
                // attemptLogin();
                if (isVcode == 1) {
                    presenter.checkSubmit();
                } else {
                    attemptLogin();
                }
                break;

            case R.id.get_vcode_btn:
                if (ETUtil.isEmpty(etAccount)) {
                    etAccount.setError("手机号不能为空");
                    return;
                }
                if (!ETUtil.isMobileNO(etAccount)) {
                    etAccount.setError("手机号格式不对");
                    return;
                }
                startTime();
                presenter.attemptIdentifyCode();
                break;
            default:
                break;
        }
    }

    @Override
    public String getPhone() {
        return getString(etAccount);
    }

    @Override
    public String getPassWord() {
        return getString(etPassword);
    }

    @Override
    public int getIsVcode() {
        return isVcode;
    }

    @Override
    public String getVcode() {
        return getString(etVcode);
    }


    @Override
    public Activity getAty() {
        return getActivity();
    }

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter(this);
    }

    /**
     * 提交问题成功后跳转到提文成功页面
     *
     * @param result
     */
    @Override
    public void askSuccess(String result) {

        showToast("提交成功");
        App.getContext().sendBroadcast(
                new Intent(Constant.ACTION_ADD_QUESTION));
        Intent intent = new Intent();
        intent.setClass(App.getContext(), MainActivity.class);
        // intent.setAction("ACTION_PAGE_TWO");
        intent.setAction("ACTION_PAGE_TWO_ADDQUESTION");
        startActivity(intent);
        if (getActivity() != null) {
            getActivity().overridePendingTransition(R.anim.slide_in_right,
                    R.anim.slide_out_left);
            getActivity().finish();
        }

    }

    @Override
    public void setError(String errorString) {
        showToast(errorString);
        // etAccount.requestFocus();
    }

    @Override
    public void identifyCode(String result) {
        if (JSONUtil.isSuccess(result)) {
            smsContent = new SmsContent(getActivity(), new Handler(), etVcode);
            // 注册短信变化监听
            App.getContext().getContentResolver().registerContentObserver(
                    Uri.parse("content://sms/"), true,
                    smsContent);
        } else {
            if (JSONUtil.getMessage(result).isEmpty()) {
                if (JSONUtil.getCode(result) == 4) {
                    setError("验证码发送频繁,稍后重试");
                }
            } else {
                setError(JSONUtil.getMessage(result));
            }
            isGetVcode = false;
        }
    }

    @Override
    public void toast(String str) {
        showToast(str);
    }

    /**
     * 开始计时
     */
    private void startTime() {
        time = 60;
        isGetVcode = true;
        new Thread() {
            public void run() {

                do {
                    SystemClock.sleep(1000);
                    if (handler != null) {
                        handler.sendEmptyMessage(--time);
                    }
                } while (time > 0 && isGetVcode == true);
                time = -1;
                handler.sendEmptyMessage(--time);
            }
        }.start();
    }

}